import md5 from 'md5';
import axios from 'axios';
import moment from 'moment';
import config from '../configuration.js';


/*乐收赢请求基地址 */
const baseUrl = 'https://open.gdyfsk.com/yfpay';
/** 乐收赢机构号 */
const inst_no = '900246';
/**乐收赢机构密钥 */
const inst_key = '7ee66094b9f54cb1ba32a95dbbf80e97';
//乐收赢文档地址：https://www.showdoc.com.cn/leshouying
const notify_url = 'https://sld.gzhkkj.net/ad/api/lsy/notify'; //支付结果通知地址
/** 乐收赢商户号 */
const mch_no = '852503190017';



function makeSign(data, secret) {
    let keys = Object.keys(data).sort();
    let paramStr = '';
    for (let index = 0; index < keys.length; index++) {
        if (keys[index] == 'sign') continue;
        let element = keys[index];
        if (paramStr.length > 0) {
            paramStr += '&';
        }
        paramStr += `${element}=${data[element]}`;
    }
    paramStr += `&key=${secret}`;
    console.log('加密前明文', paramStr);
    return md5(paramStr);
}
async function post(url, data, describe) {
    try {
        let res = await axios.post(url, data);
        let response = res.data ? res.data : {};
        console.debug(`${describe}  请求地址:${url} 请求参数 ${JSON.stringify(data)}  返回状态码:${res.status}  返回内容:${JSON.stringify(response)}`);
        return response;
    } catch (error) {
        console.error(`${describe}出错,错误原因:'` + error.message, `请求地址:${url},请求参数:${JSON.stringify(data)}`);
        return { errMsg: error.message };
    }
}
//生成毫秒时间戳加六位随机数的字符串
function generateTraceNo() {
    return moment().format('YYYYMMDDHHmmssSSS') + Math.floor(Math.random() * 1000000);
}


//小程序支付
async function applet_pay(pay_trace_no, total_amount, openid, order_body) {
    let url = `${baseUrl}/v3/minipay`;
    let data = {
        inst_no,
        mch_no,
        pay_type: '400',
        appid: config.applet_param.APPID,
        pay_trace_no,
        pay_time: moment().format('YYYYMMDDHHmmss'),
        total_amount,
        open_id: openid,
        order_body,
        notify_url
    }
    data.sign = makeSign(data, inst_key);
    let res = await post(url, data, '小程序支付');
    return res;
}

export default {
    applet_pay,
    generateTraceNo
}


// applet_pay(moment().unix(), 100, 'otCMC7KOtdtYfTNI1FrTpPjooG6A', '测试订单')
//     .then(res => {
//         console.log('支付结果:', res);
//     })
//     .catch(err => {
//         console.error('支付出错:', err);
//     });